package juc.thread.secuity;

import java.util.ArrayList;
import java.util.List;

/*
* 局部变量的线程安全问题
* */
public class Test2 {
    private static final int CIRCLE_NUM=200;
    private static final int THREAD_NUM=2;
    public static void main(String[] args) {
//        List<Object> list = new ArrayList<>();
//        Test2 test2 = new Test2();
//        for (int i = 0; i <THREAD_NUM ; i++) {
//            new Thread(()->{test2.m1();},"t"+i).start();
//        }
        Other other=new Other();
        for (int i = 0; i <THREAD_NUM ; i++) {
            new Thread(()->{other.m1();},"t"+i).start();
        }

    }
    public void m1(){//safe
        List<Object> list = new ArrayList<>();
        for (int i = 0; i <CIRCLE_NUM ; i++) {
            m2(list);
            m3(list);
        }
    }
    private void m1(List<Object>list){//unsafe
        for (int i = 0; i <CIRCLE_NUM ; i++) {
             m2(list);
             m3(list);
        }
    }
    private void m2(List<Object>list){
           list.add("add");
    }
    public void m3(List<Object>list){
           list.remove(0);
    }
    static class Other extends Test2{

        @Override
        public void m3(List<Object> list) {
            new Thread(()->{list.remove(0);}).start();
        }
    }
}
